package control

import (
	"fmt"
	ut "dockerui/utils"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
)

var upGrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func Ping(c *gin.Context) {
	//升级get请求为webSocket协议
	var (
		downloadRes int64
		messageByte []byte
		//mt  int   // message type
		resp map[string]interface{}
		ws   *websocket.Conn
		err  error
	)
	if ws, err = upGrader.Upgrade(c.Writer, c.Request, nil); err != nil {
		return
	}
	defer ws.Close()

	downloadRes = 0

	for {
		// 读取ws中的数据
		_, messageByte, err = ws.ReadMessage()
		fmt.Println("messageByte", string(messageByte))
		if err != nil {
			// 客户端关闭连接时也会进入
			fmt.Println(err)
			break
		}

		// 如果客户端发送ping就返回pong,否则数据原封不动返还给客户端
		if string(messageByte) == "ping" {
			messageByte = []byte("pong")
			if err = ws.WriteJSON(string(messageByte)); err != nil {
				break
			}
		} else {
			go dockerImagePull(string(messageByte))
			//for i := 0; i < 5; i++ {
			//	time.Sleep(2*time.Second)
			//	resp = gin.H{"message": i}
			//	err = ws.WriteJSON(resp)
			//	if err != nil {
			//		break
			//	}
			//}
			go func() {
				downloadRes = <-ut.GDockerChain.DownloadProcessChan
			}()

			for {
				fmt.Println("Download Res", downloadRes)
				if downloadRes != 0 {
					fmt.Println("download complete!")
					resp = gin.H{"message": "download complete"}
					err = ws.WriteJSON(resp)
					if err != nil {
						break
					}
					break
				} else {
					resp = gin.H{"messgae": "downloading"}
					err = ws.WriteJSON(resp)
					if err != nil {
						break
					}
				}
			}
		}
	}
}

